package com.boot2.core.web;

import com.boot2.core.SysProperties;
import com.boot2.core.conf.CookieProperties;
import com.boot2.core.utils.CheckUtil;
import com.boot2.core.utils.ServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;

/**
 * @author zhangweilin
 * @Description: 全局Cookie处理器
 * @date 2020/7/27
 */
@Component
public class CookieProcessor {

    @Autowired(required = false)
    SysProperties sysProperties;

    /**
     * 对cookie进行包装处理
     */
    public void warpCookie() {
        if (null == sysProperties) {
            return;
        }
        CookieProperties cookieProperties = sysProperties.getCookie();
        if (null == cookieProperties) {
            return;
        }
        String key = cookieProperties.getKey();
        if (CheckUtil.isEmpty(key)) {
            return;
        }

        Cookie cookie = ServletUtil.getCookie(key);
        if (cookie != null) {
            doWarpCookie(cookieProperties, cookie);
        }
    }

    private void doWarpCookie(CookieProperties cookieProperties, Cookie cookie) {
        String comment = cookieProperties.getComment();
        if (CheckUtil.isNotEmpty(comment)) {
            cookie.setComment(comment);
        }
        String domain = cookieProperties.getDomain();
        if (CheckUtil.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        String path = cookieProperties.getPath();
        if (CheckUtil.isNotEmpty(path)) {
            cookie.setPath(path);
        }
        Integer maxAge = cookieProperties.getMaxAge();
        if (null != maxAge) {
            cookie.setMaxAge(maxAge);
        }
        Boolean httpOnly = cookieProperties.getHttpOnly();
        if (null != httpOnly) {
            cookie.setHttpOnly(httpOnly);
        }
        Boolean secure = cookieProperties.getSecure();
        if (null != secure) {
            cookie.setSecure(secure);
        }
        Integer version = cookieProperties.getVersion();
        if (null != version) {
            cookie.setVersion(version);
        }
        RequestContext.getResponse().addCookie(cookie);
    }
}
